#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>

int main(int argc, char const *argv[])
{
    //创建流式套接字
    int socket_fd = socket(AF_INET,SOCK_STREAM,0);
    if(socket_fd == -1){
        perror("socket创建失败：");
        return -1;
    }

    //配置服务器地址信息
    struct sockaddr_in serverInfo = {0};

    //IPV4协议族
    serverInfo.sin_family = AF_INET;

    //端口号（主机->网络字节序）
    serverInfo.sin_port = htons(8888);

    //IP地址（点分十进制->网络字节序）
    serverInfo.sin_addr.s_addr = inet_addr("192.168.152.130");

    //连接服务器
    int ret = connect(socket_fd,(const struct sockaddr*)&serverInfo,sizeof(serverInfo));
    if(ret == -1){
        perror("connect失败：");
        return -1;
    }

    //数据收发循环
    char buf[128] = {0};
    while(true){
        //发送数据
        memset(buf,0,sizeof(buf));

        //从键盘中读取数据
        fgets(buf,sizeof(buf),stdin);

        //发送数据
        int nbTypes = send(socket_fd,buf,strlen(buf),0);
        if(nbTypes == -1){
            perror("send失败：");
            return -1;
        }
        if(strncmp(buf,"exit",4) == 0){
            break;
        }

        //接收数据
        memset(buf,0,sizeof(buf));
        int nbReads = recv(socket_fd,buf,sizeof(buf),0);
        if(nbReads == -1){
            perror("读取失败：");
            return -1;
        }else if(nbReads == 0){
            printf("服务器关闭了连接\n");
            break;
        }
        printf("服务器说：%s\n",buf);

    }
    return 0;
}
